package contextx

import (
	"context"
	"fmt"

	jsoniter "github.com/json-iterator/go"
	uuid "github.com/satori/go.uuid"
)

// WithTraceId 向context中注入traceId
func WithTraceId(parent context.Context) context.Context {
	return context.WithValue(parent, TraceIdKey, uuid.NewV4().String())
}

// GetTraceId 从context中获取traceId
func GetTraceId(ctx context.Context) string {
	if traceId, ok := ctx.Value(TraceIdKey).(string); ok {
		return traceId
	}
	return ""
}

// WithTraceUser 向context中注入traceUser
func WithTraceUser(parent context.Context, ustring string) context.Context {
	return context.WithValue(parent, TraceUserKey, ustring)
}

// UnmarshalTraceUser 从context中解析出traceUser
func UnmarshalTraceUser(ctx context.Context, ptr any) error {
	ustring, ok := ctx.Value(TraceUserKey).(string)
	if !ok {
		return fmt.Errorf("non-exist")
	}
	json := jsoniter.ConfigCompatibleWithStandardLibrary
	if err := json.Unmarshal([]byte(ustring), ptr); err != nil {
		return fmt.Errorf("failed to convert")
	}
	return nil
}

// GetTraceUserId 从context中解析traceUser的id
func GetTraceUserId(ctx context.Context) any {
	if ustring, ok := ctx.Value(TraceUserKey).(string); ok {
		var user TraceUser
		json := jsoniter.ConfigCompatibleWithStandardLibrary
		if err := json.Unmarshal([]byte(ustring), &user); err != nil {
			return user.UID
		}
	}
	return nil
}

// GetTraceUserRole 从context中解析traceUser的角色
func GetTraceUserRole(ctx context.Context) string {
	if ustring, ok := ctx.Value(TraceUserKey).(string); ok {
		var user TraceUser
		json := jsoniter.ConfigCompatibleWithStandardLibrary
		if err := json.Unmarshal([]byte(ustring), &user); err != nil {
			return user.Role
		}
	}
	return ""
}
